using System;
using System.IO;
using Framework.Library.Core.Utils.Miscellaneous;

namespace Framework.Library.Core.Utils.IO
{
    public static class StreamUtils
    {
        private const int BufferSize = 4096;

        public static void WriteStream(Stream sourceStream, Stream destinationStream)
        {
            WriteStream(sourceStream, destinationStream, BufferSize);
        }

        public static void WriteStream(Stream sourceStream, Stream destinationStream, int bufferSize)
        {
            if (sourceStream == null)
                throw new ArgumentNullException("sourceStream");

            if (destinationStream == null)
                throw new ArgumentNullException("destinationStream");

            var buffer = new byte[bufferSize];

            int bytesRead;

            // while read on the stream continues to return data,
            // write the data into the memorystream
            while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                destinationStream.Write(buffer, 0, bytesRead);
            }
        }

        public static byte[] ReadAllBytes(Stream stream)
        {
            var data = new byte[stream.Length - stream.Position];

            stream.Read(data, (int) stream.Position, data.Length);

            return data;
        }

        public static string ToString(Stream stream)
        {
            ValidationUtils.ArgumentNotNull(stream, "stream");

            string value;
            using (var sr = new StreamReader(stream))
            {
                value = sr.ReadToEnd();
            }

            return value;
        }
    }
}